package com.desaysv.svhttp.utils;

import android.app.ActivityManager;
import android.content.Context;
import android.os.Build;
import android.os.Debug;
import android.os.Process;

import androidx.annotation.RequiresApi;

/**
 * @author linzi
 * @date 2022-12-19
 */
public class MemoryUtils {
    @RequiresApi(api = Build.VERSION_CODES.M)
    public static double getRunningMemory(Context context) {
        double mem = 0.0D;
        try {
            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            // 统计进程的内存信息 totalPss
            final Debug.MemoryInfo[] memInfo = activityManager.getProcessMemoryInfo(new int[]{Process.myPid()});
            if (memInfo.length > 0) {

                /**
                 * 读取内存信息,跟Android Profiler 分析一致
                 */
                String javaMem = memInfo[0].getMemoryStat("summary.java-heap");

                String nativeMem = memInfo[0].getMemoryStat("summary.native-heap");

                String graphicsMem = memInfo[0].getMemoryStat("summary.graphics");

                String stackMem = memInfo[0].getMemoryStat("summary.stack");

                String codeMem = memInfo[0].getMemoryStat("summary.code");

                String othersMem = memInfo[0].getMemoryStat("summary.system");

                final int dalvikPss = convertToInt(javaMem, 0)
                        + convertToInt(nativeMem, 0)
                        + convertToInt(graphicsMem, 0)
                        + convertToInt(stackMem, 0)
                        + convertToInt(codeMem, 0)
                        + convertToInt(othersMem, 0);

                if (dalvikPss >= 0) {
                    // Mem in MB
                    mem = dalvikPss / 1024.0D;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mem;
    }

    /**
     * 转化为int
     *
     * @param value        传入对象
     * @param defaultValue 发生异常时，返回默认值
     * @return
     */
    public static int convertToInt(Object value, int defaultValue) {
        int result = -1;
        if (value == null || "".equals(value.toString().trim())) {
            result = defaultValue;
        } else {

            try {
                result = Integer.valueOf(value.toString());
            } catch (Exception e) {

                try {
                    return Integer.valueOf(String.valueOf(value));
                } catch (Exception e1) {

                    try {
                        result = Double.valueOf(value.toString()).intValue();
                    } catch (Exception e2) {
                        result = defaultValue;
                    }
                }
            }
        }
        return result;
    }
}
